var randomUtils = require("../../utils/randomUtils");
var textUtils = require("../../utils/textUtils");
var timeUtils = require("../../utils/timeUtils");
var clickUtils = require("../../utils/clickUtils");
var ocrUtils = require("../../utils/ocrUtils");
var adCommon = require("../adCommon");
module.exports = {
  watchAd(span, handleNextAd) {
    this.span = span;
    this.handleNextAd = handleNextAd;
    var startTime = Date.now();
    var count = 0;
    adCommon.adCount++;
    console.log("第", adCommon.adCount, "/", adCommon.maxAdCount, "个广告");
    while (true) {
      count++;
      var hasExec = timeUtils.hasExec(startTime);
      if (count % 5 == 0) {
        console.log("已经观看", hasExec, "/", this.span);
      }
      if (count >= 4 && this.isOver()) {
        this.stopAd();
        break;
      }
      if (hasExec > this.span) {
        if (count % 5 != 0) {
          console.log("已经观看", hasExec, "/", this.span, "将执行关闭广告");
        }
        this.stopAd();
        break;
      }
      sleep(2 * 1000);
    }
  },
  stopAd() {
    for (var index = 0; index < 2; index++) {
      back();
      sleep(randomUtils.getRandom(1.5, 2, 1000));
      var exitContents = [
        //prettier-disable
        "残忍离开",
        "坚持离开",
        "残忍退出",
        "坚持退出",
      ];
      var hasNextContents = [
        //prettier-disable
        "再看一个",
        "再看1个",
      ];
      if (adCommon.adCount >= adCommon.maxAdCount) {
        var TextUI = textUtils.existsOneTextStartsWith(exitContents);
        if (TextUI) {
          clickUtils.clickTextUI(TextUI);
          sleep(randomUtils.getRandom(1.5, 2, 1000));
          return;
        }
      } else {
        var TextUI = textUtils.existsOneTextStartsWith(hasNextContents);
        if (TextUI) {
          clickUtils.clickTextUI(TextUI);
          sleep(randomUtils.getRandom(1.5, 2, 1000));
          this.handleNextAd && this.handleNextAd();
          return;
        }
      }
      if (!this.inAd()) {
        console.log("没有广告，退出");
        return;
      }
    }
  },
  inAd() {
    var contents = [
      //prettier-disable
      "领取成功",
      "已领取",
      "已完成任务",
      "已获得",
      "广告",
      "反馈",
      "秒后领取奖励",
      "后可领取奖励",
      "完成任务",
    ];
    var TextUI = textUtils.existsOneTextStartsWith(contents);
    if (TextUI) {
      return TextUI;
    }
    var TextOCR = ocrUtils.captureExistsOneText(contents);
    if (TextOCR) {
      return TextOCR;
    }
    return false;
  },
  isOver() {
    var contents = [
      //prettier-disable
      "领取成功",
      "已领取",
      "已完成任务",
      "已获得",
    ];
    var TextOCR = ocrUtils.captureExistsOneText(contents);
    if (TextOCR) {
      return true;
    }
    sleep(10 * 1000);
    var TextUI = textUtils.existsOneTextStartsWith(contents);
    if (TextUI) {
      return true;
    }
  },
};
